package com.qidian.buy.cms.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;

/**
 * @author 戴着假发的程序员
 * @company 起点编程
 * @date 2024/6/13 15:10
 */
@Component
public class QiniuTools {

    // 对于AK和SK以及bucket都配置在配置文件中
// 这里的两个key从自己的七牛云后台获取
    @Value("${accessKey}")
    private String accessKey = ""; // AK
    @Value("${secretKey}")
    private String secretKey = ""; //SK
    @Value("${bucket}")
    private String bucket = ""; // 这个是空间的名字
    @Value("${qiniuUrl}")
    private String qiniuUrl;
    public String uploadFile(byte [] buff){
        String url = "";

        //构造一个带指定Region对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        // 认证
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            Response response = uploadManager.put(buff, null, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            // 访问文件的路径
            url = qiniuUrl + "/" + putRet.key;
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);
                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return url;
    };
}
